package platformio

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

type PackageFilePath string

func (path PackageFilePath) Name() string {
	splits := strings.Split(string(path), "/")
	return splits[len(splits)-1]
}

func LoadPackageFilePathsFromDir(filedir string) (packages []PackageFilePath) {
	de, err := os.ReadDir(filedir)
	if err != nil {
		return
	}

	for _, v := range de {
		path := filepath.Join(filedir, v.Name())
		packages = append(packages, PackageFilePath(path))
	}
	return
}

type PackageFileRepository struct {
}

type PackageRepository struct {
	Type string `json:"type"`
	URL  string `json:"url"`
}

type PackageFile struct {
	PackageFilePath
	Name       string      `json:"name"`
	Version    string      `json:"version"`
	Repository interface{} `json:"repository"`
}

type Packages []PackageFile

func newPackageFile(filename string) (pkg PackageFile, err error) {
	b, err := os.ReadFile(filename)
	if err != nil {
		return
	}

	err = json.Unmarshal(b, &pkg)
	if err != nil {
		return
	}
	return
}

func LoadPackageFiles(paths []PackageFilePath) (packages Packages) {
	for _, v := range paths {
		path := filepath.Join(string(v), "package.json")
		pkg, err := newPackageFile(path)
		if err != nil {
			fmt.Printf("err: %v\n", err)
			continue
		}
		packages = append(packages, pkg)
	}

	return
}
